package gw.com.android.ui.onlive.analyst;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gwtsz.gts2.hx.R;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import gw.com.android.ui.onlive.Comment;
import gw.com.android.ui.onlive.DiscussData;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.CopyShowerUtil;
import gw.com.android.utils.ImageLayoutHelper;
import www.com.library.app.Logger;
import www.com.library.util.StringFormatter;

public class AnalystReplyAdapter extends RecyclerView.Adapter<AnalystReplyAdapter.MyHolder> {

    /**
     * 左边菜单栏适配器数据对象
     */
    private Context mContext;
    private ImageWatcher watcher;
    private List<DiscussData> mDatas;

    public AnalystReplyAdapter(Activity mActivity) {
        mContext = mActivity;
    }

    public void setWatcher(ImageWatcher watcher) {
        this.watcher = watcher;
    }

    /**
     * 上拉刷新替换新数据
     */
    public void setData(List<DiscussData> list) {
        mDatas = filterData(list);

        notifyDataSetChanged();
    }

    /**
     * 下拉刷新追加数据
     */
    public void addData(List<DiscussData> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        if (mDatas == null) {
            mDatas = filterData(list);
        } else {
            mDatas.addAll(filterData(list));
        }
        notifyDataSetChanged();
    }

    /**
     * 根据position返回界面item数据对象
     */
    public DiscussData getItem(int position) {
        if (mDatas != null) {
            if (position >= 0 && position < mDatas.size()) {
                return mDatas.get(position);
            }
        }
        return null;
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.list_item_analyst_reply, parent, false);
        return new MyHolder(v);
    }

    // 由于存在同一个分析师对同一条帖子评论多次的情况，但是 后台只是返回了一条帖子数据，但是包含多条评论
    // 所以必须对这种情况的数据做出特殊处理，形成多条数据
    private List<DiscussData> filterData(List<DiscussData> list) {
        List<DiscussData> res = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            DiscussData mItem = list.get(i);
            if (mItem.comments == null || mItem.comments.size() == 0) {// 没有评论的情况
                continue;
            } else if (mItem.comments.size() == 1) {// 评论数目为1
                res.add(mItem);
            } else {//评论数目大于1
                for (int j = 0; j < mItem.comments.size(); j++) {//那么这里就要显示多条了
                    //ok,在这里构造DiscussData对象，评论用当前这个评论来替换
                    List<Comment> listComment = new ArrayList<>();
                    listComment.add(mItem.comments.get(j));
                    DiscussData temp = mItem.clone();
                    temp.comments = listComment;
                    res.add(temp);
                }
            }
        }
        return res;
    }

    @Override
    public void onBindViewHolder(MyHolder mHolder, int position) {
        DiscussData mItem = getItem(position);//item 复用
        //把时间字符串格式化
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        if (null != mItem) {
            try {
                Date date = df.parse(mItem.showDate);
                mHolder.tv_time.setText(StringFormatter.instance().toDateTimeHM(date));

                //评论内容,分析师评论内容必须存在，因为这个功能就是显示分析师对用户帖子的点评（评论内容就是点评）
                if (mItem.comments == null || mItem.comments.size() == 0) {
                    mItem.comments = new ArrayList<>();
                    mItem.comments.add(new Comment("", "", "", "无效数据！此条数据并没有返回评论内容"));
                }
                String commentContent = mItem.comments.get(0).content;
                mHolder.tv_comment_content.setText(commentContent);
                new CopyShowerUtil(mContext, mHolder.tv_comment_content);

                SpannableStringBuilder stringBuilder;
                //用户发贴的内容
                stringBuilder = new SpannableStringBuilder();
                String cbStr = mItem.userName + "  :  " + mItem.remark;
                stringBuilder.append(cbStr);//添加文字
                //添加变色部分
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#467DBF"));
                ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(Color.parseColor("#666666"));
                stringBuilder.setSpan(foregroundColorSpan, 0, mItem.userName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                stringBuilder.setSpan(foregroundColorSpan1, mItem.userName.length(), cbStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                mHolder.tv_user_post.setText(stringBuilder);
                new CopyShowerUtil(mContext, mHolder.tv_user_post);

                //帖子图片
                String s = mItem.tradeImgs;
                if (TextUtils.isEmpty(s)) {//为了兼容旧数据，必须这么做（因为旧的数据并没有tradeImgs这个字段，所以必须手动造）
                    String tradeImg = mItem.tradeImg;
                    s = "[\"" + tradeImg + "\"]";
                }
                final List<ImageView> images = new ArrayList<>();
                final List<String> urlList = new ArrayList<>();
                mHolder.ll_trade_image.removeAllViews();
                mHolder.ll_trade_image_for_only_one.removeAllViews();
                if (!TextUtils.isEmpty(s)) {
                    Type type = new TypeToken<ArrayList<String>>() {
                    }.getType();
                    List<String> shaidanImageList = new Gson().fromJson(s, type);//GSON解析数组的方式也是很诡异，和Fastjson完全不同
                    if (shaidanImageList.size() == 1) {//如果不包含中括号，就是只有一张图
                        mHolder.ll_trade_image.setVisibility(View.GONE);
                        mHolder.ll_trade_image_for_only_one.setVisibility(View.VISIBLE);
                        ImageLayoutHelper.getInstance(watcher).setSizeofSingleImg(mContext, mItem.imgSize);
                        ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, 0, mHolder.ll_trade_image_for_only_one, shaidanImageList.get(0), images, urlList, true);

                    } else {//否则就是多张图的情况，要进行JSON解析 ，json大概是这样的["1.png","2.png"]
                        mHolder.ll_trade_image.setVisibility(View.VISIBLE);
                        mHolder.ll_trade_image_for_only_one.setVisibility(View.GONE);

                        for (int i = 0; i < shaidanImageList.size(); i++) {//轮流创建imageView并且加载到布局中
                            ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, i, mHolder.ll_trade_image, shaidanImageList.get(i), images, urlList, false);
                        }
                    }
                }

                //处理分割线
                if (position + 1 == getItemCount()) {// 如果是最后一项，就隐藏分割线
                    mHolder.v_sep.setVisibility(View.GONE);
                } else {
                    mHolder.v_sep.setVisibility(View.VISIBLE);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (Exception e) {
                Logger.e("分析师点评模块-检查出异常数据，略过此条数据" + e.getLocalizedMessage());
            }
        } else {
            Log.d("sdfdxx", "居然遇到了mItem是空的情况？");
        }
    }

    @Override
    public int getItemCount() {
        if (mDatas == null) return 0;
        return mDatas.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {

        TextView tv_time;
        TextView tv_comment_content;
        TextView tv_user_post;
        LinearLayout ll_trade_image_for_only_one;
        LinearLayout ll_trade_image;
        View v_sep;

        public MyHolder(View itemView) {
            super(itemView);
            tv_time = (TextView) itemView.findViewById(R.id.tv_time);
            tv_comment_content = (TextView) itemView.findViewById(R.id.tv_comment_content);
            tv_user_post = (TextView) itemView.findViewById(R.id.tv_user_post);
            ll_trade_image = (LinearLayout) itemView.findViewById(R.id.ll_trade_image);
            ll_trade_image_for_only_one = (LinearLayout) itemView.findViewById(R.id.ll_trade_image_for_only_one);
            v_sep = itemView.findViewById(R.id.v_sep);
        }
    }
}
